<template>
  <div class="category-container">
    <div class="category-header">
      <h1 class="page-title">{{ categoryInfo.name || '分类商品' }}</h1>
    </div>
    
    <div class="products-grid" v-if="!loading && productList.length > 0">
      <div 
        v-for="product in productList" 
        :key="product.id" 
        class="product-card"
        @click="goToProductDetail(product.id)"
      >
        <div class="product-img">
          <img :src="product.imgs ? baseURL + product.imgs.split(',')[0] : ''" alt="商品图片">
        </div>
        <div class="product-info">
          <h3 class="product-name">{{ product.name }}</h3>
          <div class="product-price">
            <span class="price">¥{{ (product.specPrice * product.discount).toFixed(2) }}</span>
            <span class="original-price" v-if="product.discount < 1">¥{{ product.specPrice }}</span>
          </div>
          <div class="product-sales">已售 {{ product.sales || 0 }}</div>
        </div>
      </div>
    </div>
    
    <el-empty v-else-if="!loading && productList.length === 0" description="该分类下暂无商品" />
    
    <div class="loading-container" v-else>
      <el-skeleton :rows="5" animated />
    </div>
    
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserWebCategory'
}
</script>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';

const router = useRouter();
const route = useRoute();
const loading = ref(true);
const productList = ref([]);
const categoryInfo = ref({});
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);
const baseURL = 'http://localhost:9191';

// 获取分类ID
const getCategoryId = () => {
  return route.params.id;
};

// 加载分类信息
const loadCategoryInfo = async () => {
  const categoryId = getCategoryId();
  if (!categoryId) return;
  
  try {
    const result = await request.get(`/api/category/${categoryId}`);
    if (result && result.code === '200') {
      categoryInfo.value = result.data || {};
    }
  } catch (error) {
    console.error('获取分类信息失败:', error);
  }
};

// 加载分类商品
const loadCategoryProducts = async () => {
  loading.value = true;
  const categoryId = getCategoryId();
  
   if (!categoryId) {
    loading.value = false;
    return;
  }
  
   try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      categoryId: categoryId
    };
    
    const result = await request.get('/api/good/fullPage', { params });
    if (result && result.code === '200') {
      productList.value = result.data.records || [];
      total.value = result.data.total || 0;
    } else {
      ElMessage.error('获取分类商品失败');
      productList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取分类商品失败:', error);
    ElMessage.error('获取分类商品失败');
    productList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 跳转到商品详情页
const goToProductDetail = (productId) => {
  router.push(`/userWeb/product/${productId}`);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  loadCategoryProducts();
};

// 处理每页显示数量变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadCategoryProducts();
};

// 监听路由参数变化，当分类ID变化时重新加载商品
watch(() => route.params.id, () => {
  currentPage.value = 1;
  loadCategoryInfo();
  loadCategoryProducts();
});

onMounted(() => {
  loadCategoryInfo();
  loadCategoryProducts();
});
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.category-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  margin: 0 0 20px;
  color: #333;
}

.loading-container {
  padding: 30px 0;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.product-card {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-img {
  height: 200px;
  overflow: hidden;
}

.product-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-card:hover .product-img img {
  transform: scale(1.05);
}

.product-info {
  padding: 15px;
}

.product-name {
  margin: 0 0 10px;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-sales {
  font-size: 12px;
  color: #999;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 